<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\WechatUser;
use App\Models\UserToken;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class MyController extends Controller
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        // 暂时注释掉认证中间件
        // $this->middleware('auth:api');
    }

    /**
     * 检查用户登录状态
     */
    public function checkLogin(Request $request)
    {
        $user = $request->user();
        
        if (!$user) {
            return response()->json([
                'code' => 401,
                'msg' => '用户未登录',
                'data' => null
            ], 401);
        }

        $wechatUser = WechatUser::where('user_id', $user->id)->first();

        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'user' => [
                    'id' => $wechatUser->id,
                    'nickname' => $wechatUser->nickname,
                    'avatar' => $wechatUser->avatar,
                    'openid' => $wechatUser->openid,
                    'mobile' => $wechatUser->mobile,
                ]
            ]
        ]);
    }

    /**
     * 获取用户的个人页面数据
     */
    public function index(Request $request)
    {
        $wechatUser = WechatUser::where('user_id', $request->user()->id)->first();
        $ordersCount = Order::where('user_id', $request->user()->id)->count();
        
        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'user' => [
                    'id' => $wechatUser->id,
                    'nickname' => $wechatUser->nickname,
                    'avatar' => $wechatUser->avatar,
                    'openid' => $wechatUser->openid,
                    'mobile' => $wechatUser->mobile,
                ],
                'statistics' => [
                    'orders_count' => $ordersCount,
                    'favorites_count' => 0,
                ]
            ]
        ]);
    }

    /**
     * 更新用户信息
     */
    public function updateProfile(Request $request)
    {
        $wechatUser = WechatUser::where('user_id', $request->user()->id)->first();
        
        $validated = $request->validate([
            'nickname' => 'sometimes|string|max:50',
            'avatar' => 'sometimes|string|max:255',
            'mobile' => 'sometimes|string|max:20',
        ]);

        $wechatUser->update($validated);

        return response()->json([
            'code' => 200,
            'msg' => '个人信息更新成功',
            'data' => $wechatUser
        ]);
    }

    /**
     * 获取用户订单数量
     */
    public function getOrdersCount(Request $request, $token)
    {
        try {
            Log::info('订单数量请求开始', [
                'token' => $token,
                'url' => $request->fullUrl(),
                'method' => $request->method()
            ]);

            // 检查 token 是否存在
            if (empty($token)) {
                throw new \Exception('Token不能为空');
            }

            // 先在 user_tokens 表中查询 token
            $userToken = UserToken::where('token', $token)
                ->where('expired_at', '>', now())  // 确保 token 未过期
                ->first();
            
            if (!$userToken) {
                throw new \Exception('Token已失效或不存在');
            }

            // 查询订单数量前先检查表是否存在
            if (!Schema::hasTable('orders')) {
                throw new \Exception('orders表不存在');
            }

            // 使用 wechat_user_id 查询订单数量
            $ordersCount = Order::where('wechat_user_id', $userToken->wechat_user_id)->count();

            // 查询兑换码数量 (使用正确的字段名 wechat_users_id)
            $couponCount = \DB::table('lottery_results')
                ->where('wechat_users_id', $userToken->wechat_user_id)
                ->count();

            Log::info('订单数量查询成功', [
                'token' => $token,
                'wechat_user_id' => $userToken->wechat_user_id,
                'count' => $ordersCount,
                'coupon_count' => $couponCount
            ]);

            return response()->json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'orders_count' => $ordersCount,
                    'coupon_count' => $couponCount  // 添加兑换码数量
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('订单数量查询失败', [
                'token' => $token,
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'code' => 500,
                'msg' => $e->getMessage(),
                'data' => null
            ], 500);
        }
    }
} 